package com.knight.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.knight.dto.User;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @author knight
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @JsonView(User.SimpleView.class)
    @GetMapping
    public List<User> query(@RequestParam(required = false, name = "username")
                                    String username) {
        System.out.println(username);
        List<User> users = new ArrayList<>();
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return users;
    }

    @JsonView(User.SimpleView.class)
    @PostMapping
    public User create(@Valid @RequestBody User user, BindingResult errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().forEach(error -> System.out.println(error.getDefaultMessage()));
        }
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getId());
        System.out.println(user.getBirthday());
        user.setId("1");
        return user;
    }

    @JsonView(User.SimpleView.class)
    @PutMapping(value = "/{idxx:\\d+}")
    public User update(@Valid @RequestBody User user, BindingResult errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().forEach(error -> System.out.println(error.getDefaultMessage()));
        }
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getId());
        System.out.println(user.getBirthday());
        user.setId("1");
        return user;
    }

    /**
     * 通过使用正则表达式校验请求参数
     *
     * @param id 请求参数
     * @return
     */
    @JsonView(User.DetailView.class)
    @GetMapping(value = "/{idxx:\\d+}")
    public User getInfo(@PathVariable(name = "idxx", required = true) String id) {
        User user = new User();
        user.setUsername("Tom");
      //  throw new RuntimeException("运行异常");
        return user;
    }

    @JsonView(User.SimpleView.class)
    @DeleteMapping(value = "/{idxx:\\d+}")
    public void delete(@PathVariable(name = "idxx", required = true) String id) {
        System.out.println(id);
    }
}
